import Mock from 'mockjs';

const data = []

let sum

function handleSum() {
    sum = 0
    data.forEach((item) => sum = sum + +item.number)
}

Mock.mock('/api/data', 'get', data)

Mock.mock('/api/data/Add', 'post', (req) => {
    const newData = JSON.parse(req.body);
    newData.id = data.length + 1;
    data.push(newData);
    handleSum()

    if (sum > 150 || sum < 0) {
        data.pop();
        handleSum();
        alert("没设备了！")
    }

    return {
        data: data,
        sum: 150 - +sum,
    };
})

Mock.mock('/api/data/delete', 'post', (req) => {
    const id = JSON.parse(req.body);
    const index = data.findIndex(item => item.id === id);
    data.splice(index, 1);

    handleSum()

    return {
        data: data,
        sum: 150 - sum,
    };

})


Mock.mock('/api/data/update', 'post', (req) => {
    const result = JSON.parse(req.body);
    const id = result.id
    const {name, number, dateTime} = result.formData

    const newData = data.find(item => item.id === id);
    if (newData) {
        // 计算更新后的 sum
        const tempSum = sum - newData.number + +number;

        if (tempSum > 150 || sum < 0) {
            alert("没设备了！")
            return
        }

        newData.name = name;
        newData.number = number;
        newData.dateTime = dateTime;
        data.splice(id - 1, 1, newData);

        handleSum()

        return {
            data: data,
            sum: 150 - sum,
        };
    } else {
        return {
            code: 404,
            message: '出错了'
        };
    }
});


Mock.mock('/api/data/refresh', 'post', (req) => {
    const id = JSON.parse(req.body);
    const newData = data.find(item => item.id === id);
    data.splice(id - 1, 1, newData);

    handleSum()
    return {
        data: data,
        sum : 150-sum
    };
});

Mock.mock('/api/data/input', 'post', (req) => {
    const newData = data.find(item => item.name === req.body );
    handleSum()
    return {
        data: newData,
        originData: data,
        sum : 150-sum
    };
});





